﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using HtmlAgilityPack;
using SC2TV.Object;
using SC2TV.Tools;

namespace SC2TV.ViewModel
{
    public class StreamViewModel : BaseViewModel
    {
        public event EventHandler ChatMessageLoaded;
        private string channelName;

        public StreamViewModel()
        {
            if (DesignerProperties.IsInDesignTool) return;
            ChannelName = "Страница канала";
            ChatList = new ObservableCollection<ChatMessageViewModel>();
            var chatTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
            chatTimer.Tick += chatTimer_Tick;
            chatTimer.Start();

            //отправка статистики на сервер автора приложения
            var onlineTimer = new DispatcherTimer { Interval = TimeSpan.FromMinutes(1) };
            onlineTimer.Tick += async (s, e) =>
            {
                Guid clientID;
                IsolatedStorageSettings.ApplicationSettings.TryGetValue("clientID", out clientID);
                var requester = new Requester("http://89.222.166.108:100/api/Online?clientID=" + clientID);
                await requester.GetJson<bool>();
            };
            onlineTimer.Start();
        }

        async void chatTimer_Tick(object sender, EventArgs e)
        {
            await Load();
        }

        public string ChannelName
        {
            get { return channelName; }
            set { channelName = value; OnPropertyChanged(); }
        }

        public string Message
        {
            get { return message; }
            set { message = value; OnPropertyChanged(); }
        }

        public ObservableCollection<ChatMessageViewModel> ChatList { get; set; }

        private string channelID;
        private bool busy;
        private string message;

        internal async Task Load(string channelName = null, string streamUri = null)
        {
            if (busy) return;

            busy = true;
            try
            {
                Requester requester;
                if (!String.IsNullOrEmpty(streamUri))
                {
                    ChannelName = channelName;
                    requester = new Requester(streamUri);
                    var response = await requester.Get();
                    var html = new HtmlDocument();
                    html.LoadHtml(response.Html);
                    channelID = html.DocumentNode.SelectSingleNode("//*[@id=\"stream_player_body\"]").GetAttributeValue("class", "");
                    if (String.IsNullOrEmpty(channelID))
                        return;
                    else
                        channelID = channelID.Replace("stream-", "");
                }
                requester = new Requester("http://chat.sc2tv.ru/memfs/channel-" + channelID + ".json");
                var chat = await requester.GetJson<Chat>();
                if (chat.Item == null)
                {
                    busy = false;
                    return;
                }
                chat.Item.messages.Reverse();
                int j = 0;
                foreach (var chatMessage in chat.Item.messages)
                {
                    if (ChatList.Any(i => i.uid.Equals(chatMessage.uid) && i.date.Equals(chatMessage.date))) continue;
                    var xaml = chatMessage.message.TransformTags().AddLogin(chatMessage.name, chatMessage.role).TransformEmotions().CloseRunTag();
                    ChatList.Add(new ChatMessageViewModel
                    {
                        channelId = chatMessage.channelId,
                        date = chatMessage.date,
                        id = chatMessage.id,
                        name = chatMessage.name,
                        role = chatMessage.role,
                        roleIds = chatMessage.roleIds,
                        uid = chatMessage.uid,
                        message = xaml
                    });
                    j++;
                }
                if (ChatMessageLoaded != null && j > 0)
                    ChatMessageLoaded(this, new EventArgs());
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                busy = false;
            }
        }

        public ICommand SendMessage
        {
            get
            {
                return new ActionCommand(async () =>
                {
                    var requester = new Requester("http://chat.sc2tv.ru/gate.php?task=GetUserInfo");
                    var response = await requester.GetJson<UserInfo>();
                    requester = new Requester("http://chat.sc2tv.ru/gate.php");
                    var messageObject = new Collection<KeyValuePair<string, string>>()
                    {
                        new KeyValuePair<string, string>("task", "WriteMessage"),
                        new KeyValuePair<string, string>("message", Message),
                        new KeyValuePair<string, string>("channel_id", channelID),
                        new KeyValuePair<string, string>("token", response.Item.token)
                    };
                    var respone = await requester.Post(messageObject);
                    if (respone.StatusCode.Equals(HttpStatusCode.OK))
                        Message = String.Empty;
                });
            }
        }

        public List<Emotions> Emotions
        {
            get
            {
                return ChatParser.Emotions;
            }
        }
    }
}







